package com.authine.cloudpivot.ext.workflowevent;

import com.alibaba.cola.exception.BizException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.ext.constants.ModelConst;
import com.authine.cloudpivot.ext.dto.system.UserDto;
import com.authine.cloudpivot.ext.utils.BoServiceUtils;
import com.authine.cloudpivot.ext.utils.BoUtils;
import com.authine.cloudpivot.ext.utils.JdbcTemplateUtils;
import com.authine.cloudpivot.ext.utils.email.MailUtis;
import com.authine.hermes.app.flow.engine.delegate.event.EventType;
import com.authine.hermes.app.flow.engine.delegate.event.WorkflowEvent;
import com.authine.hermes.app.flow.engine.delegate.event.impl.FlowActivityEventImpl;
import com.authine.hermes.app.flow.engine.delegate.event.impl.WorkItemEventImpl;
import com.authine.hermes.app.flow.engine.impl.persistence.entity.WorkItemEntity;
import com.authine.hermes.app.flow.runtime.engine.listener.AbstractWorkflowEventListener;
import com.authine.hermes.app.launcher.service.BOService;
import com.authine.mvp.app.launcher.domain.utills.ApplicationContextUtils;
import com.authine.mvp.app.launcher.dto.bo.query.LoadBOQuery;
import com.authine.mvp.app.launcher.dto.bo.response.BO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

@Slf4j
@Component
public class MyWorkflowEventListener extends AbstractWorkflowEventListener {
//    private static BOService boService = ApplicationContextUtils.getBean(BOService.class);

    @Override
    public void onEvent(WorkflowEvent workflowEvent) {
        log.info("----------------------------------------------------");
        log.info("流程code:{},流程id:{},variables:{}", workflowEvent.getWorkflowCode(), workflowEvent.getWorkflowInstanceId(), workflowEvent.getVariables());
        log.info("----------------------------------------------------");
        EventType eventType = workflowEvent.getType();
        if (EventType.WF_START == eventType) {
            log.info("####################################################");
            log.info("####### 1. 流程开始了");
            String bizObjectId=this.getFlowInstanceEntityById(workflowEvent.getWorkflowInstanceId()).getBizObjectId();
            if ("order_approval_flow".equals(workflowEvent.getWorkflowCode())){
                int update = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER).putFieldAndVal("label", JSONObject.toJSONString(Arrays.asList("0")))
                        .eq("id", bizObjectId)
                        .update();
                log.info("####### 订单审批开始处理update::{}",update);
            }
        }

        if (EventType.WF_END == eventType) {
            log.info("####################################################");
            log.info("####### 2. 流程结束了");
            log.info("####################################################WF_END流程结束处理");
            String bizObjectId=this.getFlowInstanceEntityById(workflowEvent.getWorkflowInstanceId()).getBizObjectId();
            if ("order_approval_flow".equals(workflowEvent.getWorkflowCode())){
                int update = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER).putFieldAndVal("label", JSONObject.toJSONString(Arrays.asList("1")))
                        .eq("id", bizObjectId)
                        .update();
                log.info("####### 订单审批结束处理update::{}",update);
            }
        }

        if (EventType.WF_ABORT == eventType) {
            log.info("####################################################");
            log.info("####### 3. 流程作废了");
        }

        if (EventType.WF_ACTIVATE == eventType) {
            log.info("####################################################");
            log.info("####### 4. 流程激活后");
        }

        if (EventType.ACTIVITY_ACTIVATED == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################");
            log.info("####### 5. 活动激活后,活动code：{}", activityEvent.getActivityCode());
        }

        if (EventType.ACTIVITY_ACTIVATING == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################");
            log.info("####### 6. 活动激活前,活动code：{}", activityEvent.getActivityCode());
        }

        if (EventType.ACTIVITY_FINISHED == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info("####################################################");
            String workflowCode = activityEvent.getWorkflowCode();
        }

        if (EventType.ACTIVITY_CANCELED == eventType) {
            FlowActivityEventImpl activityEvent = (FlowActivityEventImpl) workflowEvent;
            log.info(" 12. 活动取消了,活动code：{}", activityEvent.getActivityCode());
        }

        if (EventType.ENTITY_CREATED == eventType) {
            log.info(" 13. 创建了1个待办任务");
        }

        if (EventType.ENTITY_UPDATED == eventType) {
            log.info(" 14. 更新了1个待办任务");
        }

        if (EventType.ENTITY_DELETED == eventType) {
            log.info(" 15. 删除了1个待办任务");
        }

        if (EventType.WORKITEM_SUBMITTED == eventType) {
            //未打印日志
            WorkItemEventImpl workItemEvent = (WorkItemEventImpl) workflowEvent;
            log.info("*************************************************");
            WorkItemEntity workItemEntity = workItemEvent.getWorkItemEntity();
            log.info(" 16. 任务提交后,活动code：{},处理人:{},BOId:{}", workItemEntity.getActivityCode(),
                    workItemEntity.getParticipant() + "-" + workItemEntity.getParticipantName(),
                    this.getFlowInstanceEntityById(workItemEvent.getWorkflowInstanceId()).getBizObjectId());
            //1、流程所有待办
            List<WorkItemEntity> list = (List<WorkItemEntity>) this.findWorkItemByWorkflowInstanceId(workflowEvent.getWorkflowInstanceId());
            log.info("所有待审批人信息::{}", JSON.toJSONString(list));
             String subject="";
             String message="";
            if (workItemEntity.getActivityCode().equals("order_approval_flow")) {
                subject="订单审批通知";
            }
//            try {
//                for (WorkItemEntity entity : list) {
//                    LoadBOQuery loadBOQuery = new LoadBOQuery();
//                    loadBOQuery.setSchemaCode("t_user");
//                    loadBOQuery.setBizObjectId(entity.getParticipant());
//                    BO bo = boService.load(loadBOQuery).getData();
//                    UserDto userDto = Optional.ofNullable(bo).map(v -> BoUtils.Map2Bo(v.getData(), UserDto.class)).orElseThrow(() -> new BizException("未查询到当前用户组织信息"));
//                    log.info("待收邮件人信息::{}", JSON.toJSONString(userDto));
//                    message="尊敬的"+userDto.getFullname()+"！您有待订单审批待处理！";
//                    MailUtis.sendEmail(userDto.getEmail(),subject,message,2);
//                }
//            } catch (Exception e) {
//                log.error("MailUtis.sendEmail Exception", e);
//            }
            log.info("*************************************************");
        }

        if (EventType.WORKITEM_REJECTED == eventType) {
            WorkItemEventImpl workItemEvent = (WorkItemEventImpl) workflowEvent;
            log.info(" 17. 任务驳回后,活动code：{}", workItemEvent.getActivityCode());
            String bizObjectId=this.getFlowInstanceEntityById(workflowEvent.getWorkflowInstanceId()).getBizObjectId();
            if ("order_approval_flow".equals(workflowEvent.getWorkflowCode())){
                int update = JdbcTemplateUtils.builder(ModelConst.T_ORDER_CUSTOMER).putFieldAndVal("label", JSONObject.toJSONString(Arrays.asList("2")))
                        .eq("id", bizObjectId)
                        .update();
                log.info("####### 订单审批结束处理update::{}",update);
            }
        }
    }
}
